package com.dian.diabetes.activity.sugar;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.dian.diabetes.R;
import com.dian.diabetes.activity.BaseFragment;
import com.dian.diabetes.activity.sugar.SugarSetFragment.CallBack;
import com.dian.diabetes.db.BloodBo;
import com.dian.diabetes.db.dao.Diabetes;
import com.dian.diabetes.tool.Config;
import com.dian.diabetes.utils.ContantsUtil;
import com.dian.diabetes.utils.DateUtil;
import com.dian.diabetes.widget.SimpleProgress;
import com.dian.diabetes.widget.anotation.ViewInject;
import com.google.gson.Gson;

/**
 * 控糖成效
 * 
 * @author hua
 * 
 */
public class SugarEffectFragment_v1 extends BaseFragment implements
		OnClickListener {
	
	String[] dates ;
	float[] arr ;
	String[] datesPre ; //一周血糖的日期类型数组( 如: 2014-2-14(晚餐前) )
	float[] arrPre ; //一周餐前血糖值的数组
	int arrPreSize = 0;//餐前的总测试数量
	String[] datesAfter ; //一周血糖的日期数组( 如: 2014-2-14(晚餐后) )
	float[] arrAfter ; //一周餐后血糖值的数组
	int arrAfterSize = 0;//餐后的 总测试数量
	
	Handler handler = new Handler();

	@ViewInject(id = R.id.back_btn)
	private Button backBtn;
	@ViewInject(id = R.id.high_value)
	private TextView highValueView;
	@ViewInject(id = R.id.mid_value)
	private TextView midValueView;
	@ViewInject(id = R.id.low_value)
	private TextView lowValueView;
	@ViewInject(id = R.id.avg_progress)
	private SimpleProgress avgProgress;
	@ViewInject(id = R.id.avg_value)
	private TextView avgValue;
	@ViewInject(id = R.id.sugar_target)
	private TextView sugarTargetValue;
	@ViewInject(id = R.id.sugar_plan)
	private TextView sugarPlan;
	@ViewInject(id = R.id.trend_img)
	private ImageView trendImg;
	@ViewInject(id = R.id.trend_value)
	private TextView trendValue;
	@ViewInject(id = R.id.sugar_effect)
	private ImageView sugarEffect;
	@ViewInject(id = R.id.sugar_effect_comment)
	private TextView sugarEffectComment;
	@ViewInject(id = R.id.check_chart_button)
	private ImageButton check_chart_button;
	@ViewInject(id = R.id.pre_week)
	private ImageButton preBtn;
	@ViewInject(id = R.id.next_week)
	private ImageButton nextBtn;
	@ViewInject(id = R.id.current_week)
	private TextView curWeek;
	@ViewInject(id = R.id.check_dinner_button)
	private ImageButton effectDinner;
	@ViewInject(id = R.id.check_dinner_text)
	private TextView effectDinner_text;

	private BloodBo diabetesBo;
	private long weekPre = 0;
	private long weekAfter = 0;

	private EChartData edata = new EChartData(); 
	private List<Diabetes> data;
	private int type = ContantsUtil.EAT_PRE;
	private DecimalFormat format;
	private float total = 0, increse = 1, persent = 1;
	private int high = 0, mid = 0, low = 0;
	private float alignment[];
	private DataTask task;
	private MealsPopDialog mealsDialog;
	private int targetMax = 15;

	public static SugarEffectFragment_v1 getInstance() {
		SugarEffectFragment_v1 fragment = new SugarEffectFragment_v1();
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ContantsUtil.EFFECT_UPDATE = false;
		diabetesBo = new BloodBo(context);
		format = new DecimalFormat("##0.0");
		
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.add(Calendar.DATE, -7);
		weekPre = calendar.getTimeInMillis();
		weekAfter = System.currentTimeMillis();
		calendar.setTimeInMillis(weekAfter);
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_sugar_effect_v1, container,
				false);
		fieldView(view);
		data = getData();
		initView();
	
		return view;
	}

	private List<Diabetes> getData(){
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.add(Calendar.DATE, -7);
		weekPre = calendar.getTimeInMillis();
		weekAfter = System.currentTimeMillis();
		calendar.setTimeInMillis(weekAfter);
		Log.e("weekPre  :  ", weekPre+"");
		Log.e("weekAfter  :  ", weekAfter+"");
		List<Diabetes> datas = diabetesBo.loadSubType(ContantsUtil.DEFAULT_TEMP_UID, weekPre,
				weekAfter + ContantsUtil.deltaDay, type);
		return datas;
	}
	
	/**
	 * 获取餐别的中文(如 : 晚餐前)
	 * @param diabetes
	 * @return 
	 */
	private String getType(Diabetes diabetes){
		String type = ""; //晚餐
		String subType = ""; // 前  后
		switch(diabetes.getType()){
			case 0: type = "早餐";break;
			case 1: type = "中餐";break;
			case 2: type = "晚餐";break;
			case 3: type = "睡";break;
		}
		switch(diabetes.getSub_type()){
			case 0: subType = "前";break;
			case 1: subType = "后";break;
		}
		return type+subType;
	}
	
	private void initView() {
		preBtn.setOnClickListener(this);
		nextBtn.setOnClickListener(this);
		sugarTargetValue.setOnClickListener(this);
		backBtn.setOnClickListener(this);
		sugarPlan.setOnClickListener(this);
		effectDinner.setOnClickListener(this);
		check_chart_button.setOnClickListener(this);
		if(nextBtn.isClickable()){
			nextBtn.setImageResource(R.drawable.forward);
		}else{
			nextBtn.setImageResource(R.drawable.forward2);
		}
		if (type == ContantsUtil.EAT_PRE) {
			effectDinner_text.setText(R.string.eat_pre);
		} else {
			effectDinner_text.setText(R.string.eat_after);
		}
		if (!ContantsUtil.EFFECT_UPDATE) {
			task = new DataTask();
			task.execute();
		} else {
			ContantsUtil.EFFECT_UPDATE = true;
			loadView();
		}
	}
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.check_chart_button:
			Log.e("type : ", type+"");
			Log.e("mid : haha", mid+"");
			Log.e("low : haha", low+"");
			Log.e("high : haha", high+"");
			Intent intent = new Intent(getActivity(),SugarChartActivity.class);
			edata.setData(data);
			intent.putExtra("edata", new Gson().toJson(edata));
			intent.putExtra("mid", mid+"");
			intent.putExtra("low", low+"");
			intent.putExtra("high", high+"");
			intent.putExtra("type", type+"");
			intent.putExtra("weekPre", DateUtil.parseToMD(weekPre));
			intent.putExtra("weekAfter", DateUtil.parseToMD(weekAfter));
			startActivity(intent);
			break;
		case R.id.sugar_target:
			toTargetSet();
			break;
		case R.id.back_btn:
			context.finish();
			break;
		case R.id.sugar_plan:
			context.startActivity(null, PlanActivity.class);
			break;
		case R.id.pre_week:
			weekAfter = weekPre;
			nextBtn.setClickable(true);
			if(nextBtn.isClickable()){
				nextBtn.setImageResource(R.drawable.forward);
			}else{
				nextBtn.setImageResource(R.drawable.forward2);
			}
			weekPre = weekPre - ContantsUtil.deltaWeek;
			curWeek.setText(DateUtil.parseToMD(weekPre) + "~"
					+ DateUtil.parseToMD(weekAfter));
			task = new DataTask();
			task.execute();
			break;
		case R.id.next_week:
			weekPre = weekAfter;
			weekAfter = weekAfter + ContantsUtil.deltaWeek;
			task = new DataTask();
			task.execute();
			break;
		case R.id.check_dinner_button:
			switchEatType(view);
			break;
		}
	}
	

	private void loadData() {
		// 基准线
		alignment = new float[] { Config.getFloatPro("levelLow" + type),
				Config.getFloatPro("levelMid" + type),
				Config.getFloatPro("levelHigh" + type) };
		// reset
		low = 0;
		mid = 0;
		high = 0;
		total = 0;
		data = diabetesBo.loadSubType(ContantsUtil.DEFAULT_TEMP_UID, weekPre,
				weekAfter + ContantsUtil.deltaDay, type);
		int size = data.size();
		float value1 = 0, value2 = 0;
		int index = 0;
		float tempTotal = 0;
		Log.e("size", data.size() + "----");
		for (Diabetes diabetes : data) {
			long timeDelta = diabetes.getCreate_time() - weekPre;
			int delta = (int) (timeDelta / ContantsUtil.deltaDay) - 1;
			float value = diabetes.getValue();
			if(delta != 0){
				if (value < alignment[0]) {
					low++;
				} else if (value >= alignment[0] && value <= alignment[2]) {
					mid++;
				} else {
					high++;
				}
			}
			if (index < data.size() / 2) {
				if (value1 == 0) {
					value1 = value;
				} else {
					value1 = (value1 + value) / 2;
				}
			} else {
				if (value2 == 0) {
					value2 = value;
				} else {
					value2 = (value2 + value) / 2;
				}
			}

			tempTotal += value;
			index++;
		}
		increse = value1 == 0 ? 0 : (value2 - value1) / value1;
		if (data.size() == 0) {
			persent = 1;
		} else {
			persent = (float)mid / data.size();
		}
		if (size == 0) {
			total = 0;
		} else {
			total = tempTotal / (size * 1.0f);
		}
	}

	private void loadView() {
		sugarTargetValue.setText(alignment[0] + "~" + alignment[2]);
		// 数值写入
		if (data.size() == 0) {
			avgProgress.setValueLevel(0, 0);
			avgValue.setText("0");
		} else {
			avgProgress.setValueLevel(total,
					Config.getBloodState(total, alignment));
			avgValue.setText(format.format(total));
		}
		setWeek(); // 周初始化
		lowValueView.setText(low + "");
		midValueView.setText(mid + "");
		highValueView.setText(high + "");
		if (increse < -0.25) {
			trendValue.setTextColor(getResources().getColor(
					R.color.trend_down_bad));
			trendImg.setImageResource(R.drawable.trend_down_normal);
		} else if (increse < 0) {
			trendValue.setTextColor(getResources().getColor(
					R.color.trend_down_normal));
			trendImg.setImageResource(R.drawable.trend_down_good);
		} else if (increse < 0.25) {
			trendValue.setTextColor(getResources().getColor(
					R.color.trend_up_normal));
			trendImg.setImageResource(R.drawable.trend_up_normal);
		} else if (increse < 0.5) {
			trendValue.setTextColor(getResources().getColor(
					R.color.trend_up_more));
			trendImg.setImageResource(R.drawable.trend_up_more);
		} else {
			trendValue.setTextColor(getResources().getColor(
					R.color.trend_up_bad));
			trendImg.setImageResource(R.drawable.trend_up_bad);
		}
		if(persent < 0.6){
			sugarEffect.setImageResource(R.drawable.cry);
			sugarEffectComment.setText(R.string.sugar_effect_comment_high);
			sugarEffectComment.setTextColor(Color.parseColor("#FF4C4C"));
		}else if(persent < 0.8 && persent >= 0.6){
			sugarEffect.setImageResource(R.drawable.angry);
			sugarEffectComment.setText(R.string.sugar_effect_comment_low);
			sugarEffectComment.setTextColor(Color.parseColor("#FFBE46"));
		}else{
			sugarEffect.setImageResource(R.drawable.smile);
			sugarEffectComment.setText(R.string.sugar_effect_comment_normal);
			sugarEffectComment.setTextColor(Color.parseColor("#00DAA7"));
		}
		trendValue.setText(((int) (increse * 100)) * 1.0f + "%");
	}

	private void toTargetSet() {
		String tag = "sugar_target_set";
		FragmentManager manager = context.getSupportFragmentManager();
		SugarSetFragment tempFragment = (SugarSetFragment) context
				.getSupportFragmentManager().findFragmentByTag(tag);
		if (tempFragment == null) {
			tempFragment = SugarSetFragment.getInstance(type);
			tempFragment.setCallBack(new CallBack() {
				@Override
				public void callBack(String persent, String value, int cur) {
					if (cur == type) {
						ContantsUtil.ENTRY_UPDATE = false;
						ContantsUtil.TOTAL_UPDATE = false;
						alignment = new float[] {
								Config.getFloatPro("levelLow" + type),
								Config.getFloatPro("levelMid" + type),
								Config.getFloatPro("levelHigh" + type) };
						Intent playAlarm = new Intent(ContantsUtil.SYCN_DATA);
						playAlarm.putExtra("state", true);
						context.startService(playAlarm);
						Config.isUpdate = true;
						task = new DataTask();
						task.execute();
					}
				}
			});
			
		}
		tempFragment.show(manager, tag);
	}

	private void setWeek() {
		long del = System.currentTimeMillis() - weekAfter;
		if (del < ContantsUtil.deltaDay && del >= 0) {
			weekAfter = System.currentTimeMillis();
			curWeek.setText("本周");
			nextBtn.setClickable(false);
			if(nextBtn.isClickable()){
				nextBtn.setImageResource(R.drawable.forward);
			}else{
				nextBtn.setImageResource(R.drawable.forward2);
			}
		} else {
			curWeek.setText(DateUtil.parseToMD(weekPre) + "~"
					+ DateUtil.parseToMD(weekAfter));
		}
	}

	private void switchEatType(View parent) {
		if (mealsDialog == null) {
			mealsDialog = new MealsPopDialog(context);
			mealsDialog.setCallBack(new MealsPopDialog.CallBack() {
				@Override
				public void callBack(int model) {
					switch (model) {
					case 0:
						Log.i("msg", "pre");
						effectDinner_text.setText(R.string.eat_pre);
						type = ContantsUtil.EAT_PRE;
						task = new DataTask();
						task.execute();
						break;
					case 1:
						Log.i("msg", "pre");
						effectDinner_text.setText(R.string.eat_after);
						type = ContantsUtil.EAT_AFTER;
						task = new DataTask();
						task.execute();
						break;
					}
				}
			});
		}
		mealsDialog.showAsDropDown(parent);
	}

	private class DataTask extends AsyncTask<Object, Object, Object> {

		@Override
		protected Object doInBackground(Object... arg0) {
			loadData();
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			loadView();
		}
	}
}
